package com.atguigu.guli.service.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.guli.service.edu.entity.ExcelSubjectData;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.listener.ExcelSubjectDataListener;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.atguigu.guli.service.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-10-26
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Autowired
    SubjectMapper subjectMapper;

    @Override
    public void importSubjects(InputStream inputStream) {
        try {
            EasyExcel.read(inputStream)
                    .head(ExcelSubjectData.class)
                    .registerReadListener(new ExcelSubjectDataListener(subjectMapper))
                    .doReadAll();
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    @Override
    public List<Subject> getNestedSubjects() {
        List<Subject> subjects = subjectMapper.selectList(null);
        Map<String,Subject> levelOneSubjects = new HashMap<>();
        for (Subject subject : subjects) {
            if("0".equals(subject.getParentId())){
                levelOneSubjects.put(subject.getId(),subject);
            }
        }
        for (Subject subject : subjects) {
            if(!"0".equals(subject.getParentId())){
                Subject levelOneSubject = levelOneSubjects.get(subject.getParentId());
                if(levelOneSubject!=null){
                    levelOneSubject.getChildren().add(subject);
                }
            }
        }
        return new ArrayList<>(levelOneSubjects.values());
    }
}
